package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.SysSequenceBo;
import org.dromara.system.domain.vo.SysSequenceVo;
import org.dromara.system.domain.SysSequence;
import org.dromara.system.mapper.SysSequenceMapper;
import org.dromara.system.service.ISysSequenceService;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.text.DecimalFormat;
import java.util.function.Function;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 序号Service业务层处理
 *
 * @author yilong.fu
 * @date 2023-05-19
 */
@RequiredArgsConstructor
@Service
public class SysSequenceServiceImpl implements ISysSequenceService {

    private final SysSequenceMapper baseMapper;

    /**
     * 查询序号
     */
    @Override
    @Transactional(readOnly = true)
    public SysSequenceVo getOne(SysSequenceBo bo, Function<LambdaQueryWrapper<SysSequence>, Boolean>
        func) {
        LambdaQueryWrapper<SysSequence> lqw = buildQueryWrapper(bo);
        func.apply(lqw);
        lqw.last("limit 0 offset 1");
        SysSequenceVo entity = this.baseMapper.selectVoOne(lqw);
        if (entity == null) {
            return entity;
        }
        return fill(entity);
    }

    /**
     * 查询序号
     */
    @Override
    @Transactional(readOnly = true)
    public SysSequenceVo getOne(SysSequenceBo bo) {

        return getOne(bo, lambdaQueryWrapper -> true);
    }

    /**
     * 查询序号
     */
    @Override
    @Transactional(readOnly = true)
    public SysSequenceVo queryById(Long id) {
        SysSequenceVo entity = baseMapper.selectVoById(id);
        if (entity == null) {
            return entity;
        }
        return fill(entity);
    }


    /**
     * 查询序号列表
     */
    @Override
    @Transactional(readOnly = true)
    public TableDataInfo<SysSequenceVo> queryPageList(SysSequenceBo bo, PageQuery pageQuery) {

        return queryPageList(bo, pageQuery, lambdaQueryWrapper -> true);
    }

    /**
     * 查询序号列表
     */
    @Override
    @Transactional(readOnly = true)
    public TableDataInfo<SysSequenceVo> queryPageList(SysSequenceBo bo, PageQuery pageQuery,
                                                      Function<LambdaQueryWrapper<SysSequence>, Boolean>
                                                          func) {
        LambdaQueryWrapper<SysSequence> lqw = buildQueryWrapper(bo);
        func.apply(lqw);
        Page<SysSequenceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<SysSequenceVo> list = result.getRecords();
        list.forEach(entity -> {
            fill(entity);
        });
        return TableDataInfo.build(result);
    }


    /**
     * 查询序号列表
     */
    @Override
    @Transactional(readOnly = true)
    public List<SysSequenceVo> queryList(SysSequenceBo bo) {
        return queryList(bo, lambdaQueryWrapper -> true);
    }

    /**
     * 查询序号列表
     */
    @Override
    @Transactional(readOnly = true)
    public List<SysSequenceVo> queryList(SysSequenceBo bo,
                                         Function<LambdaQueryWrapper<SysSequence>, Boolean>
                                             func) {
        LambdaQueryWrapper<SysSequence> lqw = buildQueryWrapper(bo);
        func.apply(lqw);
        List<SysSequenceVo> list = baseMapper.selectVoList(lqw);
        if (list == null) {
            return new ArrayList<SysSequenceVo>();
        }
        list.forEach(entity -> {
            fill(entity);
        });
        return list;
    }

    public SysSequenceVo fill(SysSequenceVo entity) {
        return entity;
    }

    private LambdaQueryWrapper<SysSequence> buildQueryWrapper(SysSequenceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysSequence> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), SysSequence::getName, bo.getName());
        lqw.eq(bo.getCurrentValue() != null, SysSequence::getCurrentValue, bo.getCurrentValue());
        lqw.eq(bo.getIncrement() != null, SysSequence::getIncrement, bo.getIncrement());
        return lqw;
    }

    /**
     * 新增序号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(SysSequenceBo bo) {
        SysSequence add = MapstructUtils.convert(bo, SysSequence.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改序号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(SysSequenceBo bo) {
        SysSequence update = MapstructUtils.convert(bo, SysSequence.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysSequence entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 删除页面
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidById(Long id, Boolean isValid) {
        return deleteWithValidByIds(CollUtil.newHashSet(id), isValid);
    }

    /**
     * 批量删除序号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional
    public String generateSequence(String seqName, String key, int number) {
        String sequence = null;
        String pattenString = StringUtils.repeat("0", number);
        long result = nextval(seqName);
        DecimalFormat formatter = new DecimalFormat(pattenString);
        sequence = formatter.format(result);
        sequence = key + sequence;
        return sequence;
    }

    /**
     * 根据SEQ名称获取序列值
     *
     * @param seqName
     * @return
     */
    @Override
    @Transactional
    public Long nextval(String seqName) {
        return this.baseMapper.nextval(seqName);
    }
}
